package com.qf.service.impl;

import com.qf.entity.Email;
import com.qf.service.IMailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @Author：刘亚康
 * @Date：2020/4/7
 * @QQ：50770284
 * @Phone：18235947935
 * @Desc : 邮件发送的实现类
 **/
@Slf4j
@Service
public class MailServiceImpl implements IMailService {
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String from;
    /**
     * 发送邮件信息
     * @return
     */
    @Override
    public void sendMailMsg(Email email) {
        //1：创建一个MimeMessige
        MimeMessage mimeMessage =javaMailSender.createMimeMessage();

        //2：创建一个发送的工具类
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);

        try {
            //设置标题
            messageHelper.setSubject(email.getTitle());
            //设置内容
            messageHelper.setText(email.getContent(),true);
            //设置发件人
            messageHelper.setFrom(from);
            //设置收件人
            messageHelper.setTo(email.getTo());
            //发送邮件
            javaMailSender.send(mimeMessage);

        } catch (MessagingException e) {
            e.printStackTrace();
        }

        log.info("给"+email.getTo()+"邮件发送成功");
    }
}
